package cn.maxwell.pet.service.impl;


import cn.maxwell.basic.service.IBaiduAiAuditService;
import cn.maxwell.basic.service.impl.BaseServiceImpl;
import cn.maxwell.basic.util.*;
import cn.maxwell.order.domain.OrderPetAcquisition;
import cn.maxwell.order.mapper.OrderPetAcquisitionMapper;
import cn.maxwell.org.domain.Employee;
import cn.maxwell.org.domain.Shop;
import cn.maxwell.org.mapper.EmployeeMapper;
import cn.maxwell.org.mapper.ShopMapper;
import cn.maxwell.pet.domain.Pet;
import cn.maxwell.pet.domain.SearchMasterMsg;
import cn.maxwell.pet.domain.SearchMasterMsgToAudit;
import cn.maxwell.pet.dto.AcceptDto;
import cn.maxwell.pet.mapper.PetMapper;
import cn.maxwell.pet.mapper.SearchMasterMsgMapper;
import cn.maxwell.pet.mapper.SearchMasterMsgToAuditMapper;
import cn.maxwell.pet.query.SearchMasterMsgQuery;
import cn.maxwell.pet.service.ISearchMasterMsgService;
import cn.maxwell.pet.service.ISearchMasterMsgToAuditService;
import cn.maxwell.user.domain.Logininfo;
import cn.maxwell.user.domain.User;
import cn.maxwell.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {

    @Autowired
    private SearchMasterMsgToAuditMapper searchMasterMsgToAuditMapper;

    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;

    @Autowired
    private IBaiduAiAuditService baiduAiAuditService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;

    @Autowired
    private PetMapper petMapper;

    /**
     * 发布寻主消息业务
     * @param searchMasterMsg
     * @param logininfo_id
     */
    @Override
    public void publish(SearchMasterMsg searchMasterMsg, Long logininfo_id) {
        //1.添加寻主消息到数据库
        //1.1.根据logininfoId获取当前登录人对象
        User user = userMapper.loadByLogininfoId(logininfo_id);
        //1.2.设置当前登录人user_id字段
        searchMasterMsg.setUser_id(user.getId());
       /* //1.3.计算最近店铺（工具类使用）
        List<Shop> shops = shopMapper.loadAll();
        Point point = DistanceUtils.getPoint(searchMasterMsg.getAddress());
        Shop nearestShop = DistanceUtils.getNearestShop(point, shops);
        searchMasterMsg.setShop_id(nearestShop.getId());*/
        //1.3.添加到数据库
        searchMasterMsgMapper.add(searchMasterMsg);



        //2.审核
        //2.1 百度ui人工智能审核（调用工具类）
        Boolean textBoolen = baiduAiAuditService.textAudit(searchMasterMsg.getName() + searchMasterMsg.getTitle() + searchMasterMsg.getAddress());
        Boolean imgBoolen = baiduAiAuditService.imageAudit(searchMasterMsg.getResources());
        SearchMasterMsgToAudit searchMasterMsgToAudit = new SearchMasterMsgToAudit();
        //2.2 如果审核通过
        if(textBoolen && imgBoolen){
            //2.3 修改状态
            searchMasterMsg.setState(1);
            searchMasterMsg.setNote("审核成功！");
            //2.4获取店铺
            List<Shop> shops = shopMapper.loadAll();
            Point point = DistanceUtils.getPoint(searchMasterMsg.getAddress());
            Shop nearestShop = DistanceUtils.getNearestShop(point, shops);
            //2.5 如果有合适店铺就绑定店铺到寻主消息
            if(nearestShop != null){
                searchMasterMsg.setShop_id(nearestShop.getId());
                //模拟发短信或发邮件
                System.out.println("你有新的订单，请尽快处理："+searchMasterMsg.getTitle());
            }else {
                searchMasterMsg.setShop_id(null);
            }
            //更新寻主消息到数据库
            searchMasterMsgMapper.update(searchMasterMsg);
            //2.6 添加审核日志
            //2.6.1 设置信息
            searchMasterMsgToAudit.setMsg_id(searchMasterMsg.getId());
            searchMasterMsgToAudit.setState(1);
            searchMasterMsgToAudit.setAudit_time(new Date());
            searchMasterMsgToAudit.setNote("审核成功，待处理");
            //2.6.2 添加审核日志
            searchMasterMsgToAuditMapper.add(searchMasterMsgToAudit);
        }else {//审核未通过
            //1.修改状态（由于前天已经给出默认状态（0：待审核））
            searchMasterMsg.setState(-1);
            //1.2 设置note信息
            searchMasterMsg.setNote("审核失败！驳回！非法内容！");
            searchMasterMsgMapper.update(searchMasterMsg);
            //2.添加审核日志
            //2.1 设置审核日志信息
            searchMasterMsgToAudit.setMsg_id(searchMasterMsg.getId());
            searchMasterMsgToAudit.setAudit_time(new Date());
            searchMasterMsgToAudit.setState(0);//驳回
            searchMasterMsgToAudit.setNote("审核失败！内容非法待修改！");
            //添加审核日志到数据库
            searchMasterMsgToAuditMapper.add(searchMasterMsgToAudit);
            //throw new BusinessException("审核失败，内容非法，重新录入内容");
        }
    }

    /**
     * 拒单业务
     * @param id
     */
    @Override
    public void reject(Long id) {
        SearchMasterMsg searchMasterMsg = searchMasterMsgMapper.loadById(id);
        searchMasterMsg.setShop_id(null);
        searchMasterMsgMapper.update(searchMasterMsg);
    }


    /**
     * 用户寻主消息查询
     * @param query
     * @param request
     * @return
     */
    @Override
    public PageList<SearchMasterMsg> userSearchMasterMsg(SearchMasterMsgQuery query, HttpServletRequest request) {
        Logininfo logininfo = (Logininfo) LoginContext.getLoginUser(request);
        User user = userMapper.loadByLogininfoId(logininfo.getId());
        query.setUser_id(user.getId());
        return super.queryPage(query);
    }

    /**
     * 待处理寻主消息查询
     * @param query
     * @param request
     * @return
     */
    @Override
    public PageList<SearchMasterMsg> toHandle(SearchMasterMsgQuery query, HttpServletRequest request) {
        query.setState(1);
        Logininfo logininfo = (Logininfo) LoginContext.getLoginUser(request);
        Employee employee = employeeMapper.loadByLogininfoId(logininfo.getId());
        if(employee.getShop_id() !=null ){
            query.setShop_id(employee.getShop_id());
        }
        return super.queryPage(query);
    }
    /**
     * 接单业务
     * @param dto
     * @param id
     */
    @Override
    public void accept(AcceptDto dto, Long id) {
        Long empId = dto.getHandler();
        Long msgId = dto.getMsgId();
        String note = dto.getNote();

        // 根据smmid查询订单，如果查的到，该订单正在处理中，
        OrderPetAcquisition order = orderPetAcquisitionMapper.loadBySmmId(msgId);
        if(order!=null){ // 之前接单了
            throw  new BusinessException("订单正在处理中。。。！");
        }

        //  1. 生成一个pet : 根据searchMasterMsg生成。
        SearchMasterMsg searchMasterMsg = searchMasterMsgMapper.loadById(msgId);

        Pet pet = searchMasterMsg2Pet(searchMasterMsg);
        // 保存,保存id
        petMapper.add(pet);

        // 2. 生成一个收购订单：
        OrderPetAcquisition opa = ininOrderPetAcquisition(dto,pet,searchMasterMsg);
        // 3. 保存订单
        orderPetAcquisitionMapper.add(opa);
    }

    /**
     * 生成一个订单对象
     * @param dto
     * @param pet
     * @return
     */
    private OrderPetAcquisition ininOrderPetAcquisition(AcceptDto dto, Pet pet,SearchMasterMsg smm) {

        // 创建一个订单对象，赋值
        OrderPetAcquisition order = new OrderPetAcquisition();

        // 随机生成一个订单编号
        order.setOrderSn(CodeGenerateUtils.generateOrderSn(smm.getUser_id()));
        // 摘要
        order.setDigest("【"+smm.getTitle()+"】");
        // 最后确认时间 定时任务
        order.setLastcomfirmtime(new Date(System.currentTimeMillis()+2*24*60*60*1000));

        order.setState(0);// 待处理
        order.setPrice(smm.getPrice());
        order.setPet_id(pet.getId());
        order.setUser_id(smm.getUser_id());
        order.setShop_id(smm.getShop_id());
        order.setAddress(smm.getAddress());
        order.setEmp_id(dto.getHandler());
        order.setSearch_master_msg_id(dto.getMsgId());
        return order;
    }

    /**
     * 通过searchMasterMsg 生成一个pet
     * @param smm
     * @return
     */
    private Pet searchMasterMsg2Pet(SearchMasterMsg smm) {
        Pet pet = new Pet();
        pet.setName(smm.getName());
        pet.setCostprice(smm.getPrice());
        pet.setType_id(smm.getPet_type());
        pet.setResources(smm.getResources());
        pet.setShop_id(smm.getShop_id());
        pet.setSearch_master_msg_id(smm.getId());
        return pet;
    }
}
